<?php

/**
 * 订单接口
 */
class OrderController extends ControllerBase {

    private $order_columns = 'order_id, serial_number, order_amount, product_count, order_time, send_time, wepay_method, leword AS remark, status, express_code, express_com, exptime';

    /**
     * 获取订单列表 [GET]
     * 接口请求地址：/order/get_list/
     * @param int $uid 用户Id
     * @param string $status 订单状态 可能的值：['unpay','payed','received','canceled','closed','refunded','delivering']
     * @param int $pageno 第几页 默认0
     * @param int $pagesize 每页显示的数量 默认20
     * @param int $device_type 设备类型 0:IOS, 1:Android <b>判断类型进行支付数据包生成, 必传</b>
     * @example 返回结果：{"retcode":0,"retmsg":[{获取订单详情中一样的结果}]}
     * @example 样品JSON : <a href="http://182.92.164.200:82/json_order_list.json" target="_blank">http://182.92.164.200:82/json_order_list.json</a>
     */
    public function get_listAction() {
        $uid = $this->request->get('uid');
        $status = $this->request->get('status');
        $pageno = InputUtil::digitDefault($this->request->get('pageno'), 0);
        $pagesize = InputUtil::digitDefault($this->request->get('pagesize'), 20);
        if ($uid > 0) {
            $sqlBulider = $this->modelsManager->createBuilder();
            $sqlBulider->where("client_id = $uid");
            if (!empty($status)) {
                $sqlBulider->andWhere("status = '$status'");
            }
            $orders = $sqlBulider
                ->columns($this->order_columns)
                ->from('Order')
                ->limit($pagesize, $pageno * $pagesize)
                ->orderBy('order_id DESC')
                ->getQuery()->execute()->toArray();
            foreach ($orders as &$od) {
                $od['details'] = Order::getOrderDetails($od['order_id']);
                // 获取快递信息
                $od['express_company'] = Order::getExpressCompany($od['express_com']);
                // 拉取地址信息
                $od['address_info'] = Order::getAddressInfo($od['order_id']);
                unset($od['express_com']);
            }
            $this->echoMsg(0, Util::digitFix($orders));
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 获取订单详情 [GET]
     * 接口请求地址：/order/get_info/
     * @param int $order_id 订单Id
     * @param int $device_type 设备类型 0:IOS, 1:Android <b>判断类型进行支付数据包生成, 必传</b>
     * @example 返回结果：{"retcode":0,"retmsg":{"order_id":订单编号,"serial_number":支付流水号,"order_amount":订单金额,
     * "product_count":商品数量,"order_time":下单时间,"send_time":发货时间,"remark":订单备注,
     * "status":订单状态,"express_code":快递单号,"exptime":null,"express_company":快递公司名称,
     * "details":[{"product_id":26,"product_name": 商品名称, "product_image": 商品图片, "sell_price":999,"product_count":999}],
     * "address_info":{
     *       "uid": 165,
     *       "uname": "asdsadsad",
     *       "phone": "asdsadsad",
     *       "province": "asdsadsad",
     *       "dist": "",
     *       "city": "asdsadsad",
     *       "poscode": "asdsadsad",
     *       "addrs": "asdsadsad"
     *   }}}
     * @example 样品JSON : <a href="http://182.92.164.200:82/json_order_info.json" target="_blank">http://182.92.164.200:82/json_order_info.json</a>
     */
    public function get_infoAction() {
        $order_id = $this->request->get('order_id');
        $deviceType = InputUtil::digitDefault($this->request->get('device_type'), 0);
        if ($order_id > 0) {
            $order = Order::findFirst(["order_id = $order_id", 'columns' => $this->order_columns])->toArray();
            // 获取快递信息
            $order['express_company'] = Order::getExpressCompany($order['express_com']);
            unset($order['express_com']);
            // 获取订单详情
            $order['details'] = Order::getOrderDetails($order_id);
            // 拉取地址信息
            $order['address_info'] = Order::getAddressInfo($order_id);
            // 是否未支付
            if ($order['status'] == 'unpay' || $order['status'] == 'canceled') {
                $paymethod = $order['wepay_method'];
                // 支付签名 [微信支付]
                if ($paymethod == 0) {
                    $paySignPackage = Payment::createWxpayPackage($order['order_id'], $deviceType);
                }
                // 支付签名 [支付宝]
                if ($paymethod == 1) {
                    $paySignPackage = Payment::createAlipayPackage($order['order_id']);
                }
            } else {
                $paySignPackage = null;
            }
            $order['payment_package'] = $paySignPackage;
            $this->echoMsg(0, Util::digitFix($order));
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 创建订单 [POST]
     * 接口请求地址：/order/create/
     * @param int $uid 用户Id
     * @param array $order_data [{product_id:1,product_count:1},{product_id:1,product_count:1}] 商品列表
     * @param int $aid 地址Id
     * @param int $credit 使用多少积分抵扣
     * @param int $paymethod 支付方式，0微信支付，1支付宝，2货到付款
     * @param string $exptime 配送时间 如果为立即配送，为空字符串
     * @param int $device_type 设备类型 0:IOS, 1:Android <b>判断类型进行支付数据包生成, 必传</b>
     * @example 样品JSON : <a href="http://182.92.164.200:82/json_create_order.json" target="_blank">http://182.92.164.200:82/json_create_order.json</a>
     * @example 返回结果：{"retcode":0,"retmsg": 获取订单详情中一样的结果}
     * @example 如果不是货到付款，返回数据中将带有 <b>payment_package</b> 字段，支付使用。参数详情见payment接口
     */
    public function createAction() {
        $uid = InputUtil::digitDefault($this->request->getPost('uid'), 0);
        $aid = InputUtil::digitDefault($this->request->getPost('aid'), 0);
        $orderdata = $this->request->getPost('order_data');
        $credit = InputUtil::digitDefault($this->request->getPost('credit'), 0);
        $exptime = InputUtil::strDefault($this->request->getPost('exptime'), '');
        $paymethod = InputUtil::digitDefault($this->request->getPost('paymethod'), 0);
        $deviceType = InputUtil::digitDefault($this->request->getPost('device_type'), 0);
        if ($uid > 0 && $aid > 0 && !empty($orderdata)) {
            try {
                $order = new Order();
                $order->serial_number = date("Ymdhis") . mt_rand(10, 99);
                $order->client_id = $uid;
                $order->order_time = date('Y-m-d H:i:s');
                $order->address_hash = $aid;
                $order->express_code = '';
                $order->express_com = '';
                // 使用的积分
                $creditEx = Settings::get("credit_ex");
                // 积分折扣金额
                $order->order_dixian = $credit * floatval($creditEx);
                // 使用的积分
                $order->order_credit = $credit;
                // 配送时间
                $order->exptime = trim($exptime);
                // 支付方式
                $order->wepay_method = $paymethod;
                // 商品数量
                $order_count = 0;
                // 订单金额
                $order_amount = 0;
                // 货到付款方式，直接已支付
                $paymethod == 2 && $order->status = 'payed';
                // 创建订单
                $order->save();
                // 积分计算
                if ($credit > 0) {
                    $user = User::findFirst("client_id = $uid");
                    if ($user) {
                        if ($user->client_credit < $credit) {
                            return $this->echoErrcode(ErrorCode::$ERR_ORDER_CREDITNOTENG);
                        } else {
                            // 减去积分
                            $user->client_credit -= $credit;
                            if ($user->save()) {
                                // 记录变动历史
                                CreditRecord::log($user->client_id, -1 * $credit, 0, $order->order_id, '订单积分抵现-' . $credit);
                            }
                            $user->save();
                        }
                    } else {
                        // 用户不存在
                        return $this->echoErrcode(ErrorCode::$ERR_ORDER_USER_NOTEXT);
                    }
                }
                // 写入订单详情
                if (!is_array($orderdata)) {
                    $orderdata = json_decode($orderdata, true);
                }
                // 写入订单详情
                foreach ($orderdata as $od) {
                    $productInfo = Product::findFirst("product_id = {$od['product_id']}");
                    $order_amount += floatval($productInfo->sell_price) * intval($od['product_count']);
                    $order_count += $od['product_count'];
                    // 写入订单详情
                    $order_detail = new OrderDetail();
                    $order_detail->order_id = $order->order_id;
                    $order_detail->product_id = $od['product_id'];
                    $order_detail->product_count = $od['product_count'];
                    $order_detail->product_discount_price = floatval($productInfo->sell_price);
                    $order_detail->save();
                }
                // 更新信息
                $order = Order::findFirst("order_id = $order->order_id");
                // 订单金额（原价减去积分抵现）
                $order->order_amount = $order_amount - $order->order_dixian;
                // 商品数量
                $order->product_count = $order_count;
                $order->save();
                // 写入订单地址
                $address = Address::findFirst("aid = $aid");
                if ($address) {
                    $oaddress = new OrderAddress();
                    $oaddress->client_id = $uid;
                    $oaddress->order_id = $order->order_id;
                    $oaddress->user_name = $address->uname;
                    $oaddress->tel_number = $address->phone;
                    $oaddress->province = $address->province;
                    $oaddress->city = $address->city;
                    $oaddress->area = $address->dist;
                    $oaddress->address = $address->addrs;
                    $oaddress->postal_code = $address->poscode;
                    $oaddress->save();
                }
                // 返回数据
                $orderArray = Order::findFirst([
                    "order_id = $order->order_id",
                    'columns' => $this->order_columns
                ])->toArray();
                $orderArray['details'] = Order::getOrderDetails($order->order_id);
                $orderArray['address_info'] = $address->toArray();
                // 支付签名 [微信支付]
                if ($paymethod == 0) {
                    $paySignPackage = Payment::createWxpayPackage($order->order_id, $deviceType);
                }
                // 支付签名 [支付宝]
                if ($paymethod == 1) {
                    $paySignPackage = Payment::createAlipayPackage($order->order_id, $deviceType);
                }
                // 支付签名数据包
                $orderArray['payment_package'] = $paySignPackage;
                unset($orderArray['address_hash']);
                $this->echoMsg(0, $orderArray);
            } catch (Exception $ex) {
                $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 确认收货 [POST]
     * 接口请求地址：/order/confirm/
     * @param int $order_id 订单Id
     * @example 返回结果：{"retcode":0,"retmsg":"Success"}
     */
    public function confirmAction() {
        $orderId = $this->request->getPost('order_id');
        if ($orderId > 0) {
            $order = Order::findFirst("order_id = $orderId");
            if ($order) {
                try {
                    $order->status = 'received';
                    // 处理积分问题
                    $user = User::findFirst("client_id = $order->client_id");
                    if ($user) {
                        // 订单返积分比例
                        $credit_order_amount = floatval(Settings::get('credit_order_amount'));
                        if ($credit_order_amount > 0) {
                            // 计算订单奖励积分
                            $creditAdd = $order->order_amount * $credit_order_amount;
                            // 订单信息记录
                            $order->order_credit_add = $creditAdd;
                            // 用户积分变动
                            $user->client_credit += $creditAdd;
                            if ($user->save()) {
                                // 记录变动历史
                                CreditRecord::log($user->client_id, $creditAdd, 0, $order->order_id, '订单赠送积分+' . $creditAdd);
                            }
                        }
                    }
                    $order->save();
                    $this->echoSuccess();
                } catch (Exception $ex) {
                    $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
                }
            } else {
                $this->echoErrcode(ErrorCode::$ERR_ORDER_NOTEXT);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 取消订单 [POST]
     * 接口请求地址：/order/cancel/
     * @param int $order_id 订单Id
     * @example 返回结果：{"retcode":0,"retmsg":"Success"}
     */
    public function cancelAction() {
        $orderId = $this->request->getPost('order_id');
        if ($orderId > 0) {
            $order = Order::findFirst("order_id = $orderId");
            if ($order) {
                try {
                    // 如果订单未支付 而且又使用了积分 退回 其他已支付已发货的订单在退款中处理
                    if ($order->status == 'unpay' && $order->order_credit > 0) {
                        $user = User::findFirst("client_id = $order->client_id");
                        if ($user) {
                            // 回扣订单使用的积分
                            try {
                                $order->order_credit = 0;
                                $user->client_credit += $order->order_credit;
                                if ($user->save()) {
                                    CreditRecord::log($user->client_id, $order->order_credit, 0, $order->order_id, '订单取消返回积分+' . $order->order_credit);
                                }
                            } catch (Exception $ex) {
                                // 积分回扣错误
                                Util::log('order_cancel_error_credit:' . PHP_EOL . json_encode($_POST) . PHP_EOL . $ex->getMessage());
                            }
                        }
                    }
                    $order->status = 'canceled';
                    $order->save();
                    $this->echoSuccess();
                } catch (Exception $ex) {
                    $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
                }
            } else {
                $this->echoErrcode(ErrorCode::$ERR_ORDER_NOTEXT);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 删除订单 [POST]
     * 接口请求地址：/order/delete/
     * @param int $order_id 订单Id
     * @example 只有已取消的订单才能被删除
     * @example 返回结果：{"retcode":0,"retmsg":"Success"}
     */
    public function deleteAction() {
        $orderId = $this->request->getPost('order_id');
        if ($orderId > 0) {
            $order = Order::findFirst("order_id = $orderId");
            if ($order) {
                try {
                    if ($order->statue == 'canceled') {
                        $order->delete();
                        $this->echoSuccess();
                    } else {
                        $this->echoErrcode(ErrorCode::$ERR_ORDER_DELETE_FAILED);
                    }
                } catch (Exception $ex) {
                    $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
                }
            } else {
                $this->echoErrcode(ErrorCode::$ERR_ORDER_NOTEXT);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 订单评价 [POST]
     * 接口请求地址：/order/comment/
     * @param int $product_id 商品Id
     * @param int $uid 用户Id
     * @param string $content 评价内容
     * @example 返回结果：{"retcode":0,"retmsg":"Success"}
     */
    public function commentAction() {
        $uid = $this->request->getPost('uid');
        $product_id = $this->request->getPost('product_id');
        $content = $this->request->getPost('content');
        if ($product_id > 0 && $content != '' && $uid > 0) {
            try {
                $comment = new OrderComment();
                $comment->uid = $uid;
                $comment->mtime = date('Y-m-d H:i:s');
                $comment->content = $content;
                $comment->product_id = $product_id;
                $comment->save();
                $this->echoSuccess();
            } catch (Exception $ex) {
                $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 获取未评价订单列表 [GET]
     * 接口请求地址：/order/get_uncomment_list/
     * @param int $pageno 第几页 默认0
     * @param int $pagesize 每页显示的数量 默认20
     * @param int $uid 用户Id
     * @example 返回结果：{"retcode":0,"retmsg":[{"product_id":商品Id,"product_name":商品名称,"product_image":"商品图片","order_id":订单编号,"product_count":商品数量,"sell_price":商品单价}]}
     */
    public function get_uncomment_listAction() {
        $uid = InputUtil::digitDefault($this->request->get('uid'), 0);
        $pageno = InputUtil::digitDefault($this->request->get('pageno'), 0);
        $pagesize = InputUtil::digitDefault($this->request->get('pagesize'), 20);
        if ($uid > 0) {
            global $config;
            $sqlBulider = $this->modelsManager->createBuilder();
            $sqlBulider->where("client_id = $uid");
            $sqlBulider->andWhere("status = 'received'");
            $orders = $sqlBulider->columns("ods.product_id,pd.product_name,pd.catimg AS product_image,od.order_id,ods.product_count,product_discount_price AS sell_price")
                ->from(['ods' => 'OrderDetail'])
                ->leftJoin('Order', 'od.order_id = ods.order_id', 'od')
                ->leftJoin('Product', 'pd.product_id = ods.product_id', 'pd')
                ->where('ods.is_commented = 0')
                ->limit($pagesize, $pageno * $pagesize)
                ->orderBy('od.order_id DESC')
                ->getQuery()->execute()->toArray();
            foreach ($orders as &$product) {
                $product['product_image'] = $config->base->domainbase . 'uploads/product_hpic/' . $product['product_image'];
            }
            $this->echoMsg(0, Util::digitFix($orders));
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 获取订单可用积分 [POST]
     * 接口请求地址：/order/get_credit_available/
     * @param int $uid 用户Id
     * @param float $amount 订单金额
     * @example 返回结果：{"retcode":0,"retmsg":{"available": 可用的积分数额(int), "equal": 可抵现金额(float)}}
     */
    public function get_credit_availableAction() {
        $uid = $this->request->getPost('uid');
        $amount = $this->request->getPost('amount');
        if ($uid > 0 && $amount > 0) {
            $user = User::findFirst("client_id = $uid");
            if ($user) {
                $final = 0;
                $credit = $user->client_credit;
                if ($credit > 0) {
                    $ava = CreditAvailable::findFirst("$amount BETWEEN cfrom AND cto");
                    if (!$ava) {
                        // 查找最近的
                        $ava = CreditAvailable::findFirst(["cfrom <= $amount", 'order' => 'cfrom DESC']);
                    }
                    if ($ava) {
                        $avacredit = $ava->credit;
                        if ($credit > $avacredit) {
                            $final = $avacredit;
                        } else {
                            $final = $credit;
                        }
                    }
                }
                if ($final == 0) {
                    $equal = 0;
                } else {
                    // 查询积分兑换比例
                    $creditEx = Settings::get("credit_ex");
                    $equal = $final * $creditEx;
                }
                $this->echoMsg(0, ['available' => intval($final), 'equal' => round($equal, 2)]);
            } else {
                $this->echoErrcode(ErrorCode::$ERR_ORDER_CREDIT_AVA);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

}
